package com.hemaapp.yjnh;

import java.io.File;
import java.io.FileOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog;
import com.hemaapp.yjnh.activity.BookProductionDetailActivity;
import com.hemaapp.yjnh.activity.CmnProductionDetailActivity;
import com.hemaapp.yjnh.activity.CustomizeProductionDetailActivity;
import com.hemaapp.yjnh.activity.FarmerCropDetailActivity;
import com.hemaapp.yjnh.activity.LoginActivity;
import com.hemaapp.yjnh.activity.MainActivity;
import com.umeng.socialize.bean.SHARE_MEDIA;

import xtom.frame.XtomActivityManager;
import xtom.frame.util.XtomFileUtil;
import xtom.frame.util.XtomSharedPreferencesUtil;
import xtom.frame.util.XtomTimeUtil;

import android.*;
import android.Manifest;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.text.InputFilter;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

/**
 * 工具类
 */
public class BaseUtil {
	private static double EARTH_RADIUS = 6378.137;// 地球半径
    public static final SHARE_MEDIA[] shareList = new SHARE_MEDIA[]
            {
                    SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE
            };

	private static double rad(double d) {
		return d * Math.PI / 180.0;
	}

	/**
	 * 根据手机分辨率从dp转成px
	 * 
	 * @param context
	 * @param dpValue
	 * @return
	 */
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}
  
    /** 
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp 
     */  
    public static int px2dip(Context context, float pxValue) {  
        final float scale = context.getResources().getDisplayMetrics().density;  
        return (int) (pxValue / scale + 0.5f);  
    }  
	
	public static String transDuration(long duration) {
		String ds = "";
		long min = duration / 60;
		if (min < 60) {
			ds += (min + "分钟");
		} else {
			long hour = min / 60;
			long rm = min % 60;
			if (rm > 0)
				ds += (hour + "小时" + rm + "分钟");
			else
				ds += (hour + "小时");
		}
		return ds;
	}

	public static String transDistance(float distance) {
		String ds = "";
		if (distance < 1000) {
			ds += (distance + "米");
		} else {
			float km = distance / 1000;
			ds += (String.format(Locale.getDefault(), "%.2f", km) + "千米");
		}
		return ds;
	}

	/**
	 * 计算两点间的距离
	 * 
	 * @param lat1
	 * @param lng1
	 * @param lat2
	 * @param lng2
	 * @return
	 */
	public static Double GetDistance(double lat1, double lng1, double lat2,
			double lng2) {
		double radLat1 = rad(lat1);
		double radLat2 = rad(lat2);
		double a = radLat1 - radLat2;
		double b = rad(lng1) - rad(lng2);

		double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
				+ Math.cos(radLat1) * Math.cos(radLat2)
				* Math.pow(Math.sin(b / 2), 2)));
		s = s * EARTH_RADIUS;
		s = Math.round(s * 10000) / 10000;
		return s;
	}

	/**
	 * 隐藏用户名
	 * 
	 * @param nickname
	 * @return
	 */
	public static String hideNickname(String nickname) {
		int length = nickname.length();
		String first = nickname.substring(0, 1);
		String last = nickname.substring(length - 1, length);
		String x = "";
		for (int i = 0; i < length - 2; i++) {
			x += "*";
		}
		return first + x + last;
	}
	
	/**是否已经登录
	 * @return
	 */
	public static boolean isLogin(){
		if(BaseApplication.getInstance().getUser()==null){
			return false;
		}else{
			return true;
		}
	}

	public static void checkLogin(Context mContext){
		Intent it=new Intent(mContext,LoginActivity.class);
		mContext.startActivity(it);
	};

	public static void exit(Context context) {
		XtomActivityManager.finishAll();
	}

	
	/**功能描述：[是否早于当前时间]
	 * 程序作者：WZL  
	 * 编写时间：[2015年4月9日]-[下午3:44:49]
	 * @param endtime
	 * @return  true 早 false 晚
	 */
	public static boolean isBefore(String endtime){
		Date nowDate = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
				Locale.getDefault());
		try {
			Date endDate = sdf.parse(endtime);
			return nowDate.before(endDate);
		} catch (ParseException e) {
			e.printStackTrace();
			return false;
		}
	}
	/**
	 * 
	 * 功能描述：[重置listview高度]
	 * 程序作者：WZL  
	 * 编写时间：[2015年4月9日]-[下午9:11:43]
	 * @param listView
	 */
	public static void setListViewHeightBasedOnChildren(ListView listView) {  
        ListAdapter listAdapter = listView.getAdapter();   
        if (listAdapter == null) {  
            // pre-condition  
            return;  
        }  
  
        int totalHeight = 0;  
        for (int i = 0; i < listAdapter.getCount(); i++) {  
            View listItem = listAdapter.getView(i, null, listView);  
            listItem.measure(0, 0);  
            totalHeight += listItem.getMeasuredHeight();  
        }  
  
        ViewGroup.LayoutParams params = listView.getLayoutParams();  
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));  
        listView.setLayoutParams(params);
    }  
	
	/**
	 * 重新计算listView的高度
	 * @param listView
	 */
	public static int setListViewHeightBasedOnChildren(ListView listView,int moreHeight, Context context) {  
        ListAdapter listAdapter = listView.getAdapter();   
        if (listAdapter == null) {
            // pre-condition  
            return 0;  
        }  
  
        int totalHeight = 0;  
        if(listAdapter.getCount()>0){
        	for (int i = 0; i < listAdapter.getCount(); i++) {
                View listItem = listAdapter.getView(i, null, listView);  
                listItem.measure(0, 0);  
                totalHeight += listItem.getMeasuredHeight();  
            }      
        }
        moreHeight = dip2px(context, moreHeight);
        totalHeight+=moreHeight;
        ViewGroup.LayoutParams params = listView.getLayoutParams();  
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));  
        listView.setLayoutParams(params); 
        return params.height;
        
    }

	/**将日期转换为制定的时间格式的字符串
	 * @param date
	 * @param format
	 * @return
	 */
	public static String transString(Date date, SimpleDateFormat format){
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String str = format.format(date);
		return str;
	}

	/**
	 * 转换时间显示形式(与当前系统时间比较),在显示即时聊天的时间时使用
	 * 
	 * @param time
	 *            时间字符串
	 * @return String
	 */
	public static String transTimeChat(String time) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
					Locale.getDefault());
			String current = XtomTimeUtil.getCurrentTime("yyyy-MM-dd HH:mm:ss");
			String dian24 = XtomTimeUtil.TransTime(current, "yyyy-MM-dd")
					+ " 24:00:00";
			String dian00 = XtomTimeUtil.TransTime(current, "yyyy-MM-dd")
					+ " 00:00:00";
			Date now = null;
			Date date = null;
			Date d24 = null;
			Date d00 = null;
			try {
				now = sdf.parse(current); // 将当前时间转化为日期
				date = sdf.parse(time); // 将传入的时间参数转化为日期
				d24 = sdf.parse(dian24);
				d00 = sdf.parse(dian00);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			long diff = now.getTime() - date.getTime(); // 获取二者之间的时间差值
			long min = diff / (60 * 1000);
			if (min <= 5)//5分钟之内
				return "刚刚";
			if (min < 60)//1个小时之内
				return min + "分钟前";

			if (now.getTime() <= d24.getTime()
					&& date.getTime() >= d00.getTime())
				return "今天" + XtomTimeUtil.TransTime(time, "HH:mm");

			int sendYear = Integer
					.valueOf(XtomTimeUtil.TransTime(time, "yyyy"));
			int nowYear = Integer.valueOf(XtomTimeUtil.TransTime(current,
					"yyyy"));
			if (sendYear < nowYear)
				return XtomTimeUtil.TransTime(time, "yyyy-MM-dd HH:mm");
			else
				return XtomTimeUtil.TransTime(time, "MM-dd HH:mm");
		} catch (Exception e) {
			return null;
		}

	}

    // 获取软件Logo文件地址
    public static String getLogoImagePath(Context context) {
        String imagePath;
        try {
            String cachePath_internal = XtomFileUtil.getCacheDir(context)
                    + "/images/";// 获取缓存路径
            File dirFile = new File(cachePath_internal);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            imagePath = cachePath_internal + "icon.png";
            File file = new File(imagePath);
            if (!file.exists()) {
                file.createNewFile();
                Bitmap pic = BitmapFactory.decodeResource(
                        context.getResources(), R.drawable.ic_launcher);
                FileOutputStream fos = new FileOutputStream(file);
                pic.compress(Bitmap.CompressFormat.PNG, 100, fos);
                fos.flush();
                fos.close();
            }
        } catch (Throwable t) {
            t.printStackTrace();
            imagePath = null;
        }
        return imagePath;
    }

//	public final static DisplayImageOptions avatarImageOptions  = new DisplayImageOptions.Builder()
//			.showImageOnLoading(R.drawable.default_rabbit_grey)
//			.showImageOnFail(R.drawable.default_rabbit_grey)
//			.cacheInMemory(true)
//			.cacheOnDisk(true)
//			.bitmapConfig(Bitmap.Config.RGB_565)
//			.build();
//
//	public final static DisplayImageOptions smallImageOptions  = new DisplayImageOptions.Builder()
//			.showImageOnLoading(R.drawable.no_pic_small)
//			.showImageOnFail(R.drawable.no_pic_small)
//			.showImageForEmptyUri(R.drawable.no_pic_small)
//			.cacheInMemory(true)
//			.cacheOnDisk(true)
//			.bitmapConfig(Bitmap.Config.RGB_565)
//			.build();
//
//    public final static DisplayImageOptions midImageOptions  = new DisplayImageOptions.Builder()
//            .showImageOnLoading(R.drawable.no_pic_mid)
//            .showImageOnFail(R.drawable.no_pic_mid)
//			.showImageForEmptyUri(R.drawable.no_pic_mid)
//            .cacheInMemory(true)
//            .cacheOnDisk(true)
//            .bitmapConfig(Bitmap.Config.RGB_565)
//            .build();
//
//    public final static DisplayImageOptions bigImageOptions  = new DisplayImageOptions.Builder()
//            .showImageOnLoading(R.drawable.no_pic_big)
//            .showImageOnFail(R.drawable.no_pic_big)
//			.showImageForEmptyUri(R.drawable.no_pic_big)
//            .cacheInMemory(true)
//            .cacheOnDisk(true)
//            .bitmapConfig(Bitmap.Config.RGB_565)
//            .build();
//
//	public final static DisplayImageOptions circleAvatarOptions  = new DisplayImageOptions.Builder()
//			.showImageOnLoading(R.drawable.default_rabbit_grey)
//			.showImageOnFail(R.drawable.default_rabbit_grey)
//			.showImageForEmptyUri(R.drawable.default_rabbit_grey)
//			.cacheInMemory(true)
//			.cacheOnDisk(true)
//			.bitmapConfig(Bitmap.Config.RGB_565)
//			.displayer(new CircleBitmapDisplayer(0))
//			.build();

    /**创建帖子点击跳转Intent
     * @param context
     * @param blogType
     * @return
     */
    public static Intent createBlogIntent(Context context, String blogType) {
        Intent intent = new Intent();
        // 0唠嗑帖子；0唠嗑帖子；1田家农货；2有机；3地标；4村游；5田家日志；6特产；9乐乐；11粮库；21农需
        // 71走走房车露营；72走走自驾车露营；73走走帐篷露营；74走走商品区；75走走房车；76景区商品
        // 81苗木；82花卉；83家电；84日用品；10众农
		if (TextUtils.isEmpty(blogType)) {
			intent.setClass(context, MainActivity.class);
		}else if (blogType.equals("2") || blogType.equals("3")
                || blogType.equals("6") || blogType.equals("11") || blogType.equals("21")
                || blogType.equals("81") || blogType.equals("82")
                || blogType.equals("83") || blogType.equals("84")
                || blogType.equals("75")) {//
            intent.setClass(context, CmnProductionDetailActivity.class);
        }else if (blogType.equals("1")) {// 田家农货
            intent.setClass(context, FarmerCropDetailActivity.class);
        }else if (blogType.equals("4") || blogType.equals("9") || blogType.equals("76")) {
            intent.setClass(context, BookProductionDetailActivity.class);
            intent.putExtra("type", 1);
        }else if (blogType.equals("71") || blogType.equals("72")
                || blogType.equals("73") || blogType.equals("74")) {
            intent.setClass(context, BookProductionDetailActivity.class);
            intent.putExtra("type", 2);
        }else if (blogType.equals("-1")) {// 田家定制产品
            intent.setClass(context, CustomizeProductionDetailActivity.class);
        }else {
            intent.setClass(context, CmnProductionDetailActivity.class);
        }
        return intent;
	}
	/**判断是否是第一次登录
	 *
     * @param context
     * @return true是第一次，false不是第一次
     */
	public static boolean checkVirgin(Context context) {
		String isVirgin = XtomSharedPreferencesUtil.get(context, "isVirgin");
		boolean virgin = "false".equals(isVirgin);//非false，全部认为是第一次
        if (!virgin)//如果是第一次，就将其置为false
            XtomSharedPreferencesUtil.save(context, "isVirgin", "false");
		return !virgin;
	}

	public static String transNull(String content) {
        if (content == null || content.equals("null"))
            content = "";
        return content;
    }

    /**在TextView显示的内容中，插入粮票符号
     * @param textView 要显示的TextView
     * @param stampId 粮票的图片资源id
     */
    public static void addStampSign(Context context, TextView textView, int stampId) {
        final SpannableString ss = new SpannableString("stamp");
        Drawable d = context.getResources().getDrawable(stampId);
        d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
        ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
        ss.setSpan(span, 0, "stamp".length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        textView.append(ss);
    }

	/**给Edittext加入emoji的过滤，禁止输入emoji
     * 同时最多输入20个字符
	 * @param et
	 */
	public static void setEmojiFilter(EditText et) {
		InputFilter emojiFilter = new InputFilter() {
			Pattern pattern = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]", Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);

			@Override
			public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
				Matcher matcher = pattern.matcher(source);
				if(matcher.find()){
					return "";
				}
				return null;
			}
		};
        InputFilter lengthFilter = new InputFilter.LengthFilter(20);
		et.setFilters(new InputFilter[]{emojiFilter, lengthFilter});
        et.setSingleLine();
	}

	public static void initWebview(WebView webView) {
		// 支持javascript
		webView.getSettings().setJavaScriptEnabled(true);
		// 设置可以支持缩放
		webView.getSettings().setSupportZoom(true);
		// 设置出现缩放工具
		webView.getSettings().setBuiltInZoomControls(false);
		// 扩大比例的缩放
		webView.getSettings().setUseWideViewPort(true);
		// 自适应屏幕
		webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
		webView.getSettings().setLoadWithOverviewMode(true);
		// 取消显示滚动条
		webView.setVerticalScrollBarEnabled(false);
		webView.setHorizontalScrollBarEnabled(false);
		webView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				return true;
			}
		});

		webView.getSettings().setSavePassword(true);
		webView.getSettings().setSaveFormData(true);
		webView.getSettings().setGeolocationEnabled(true);
		webView.getSettings().setGeolocationDatabasePath("/data/data/org.itri.html5webView/databases/");     // enable Web Storage: localStorage, sessionStorage
		webView.getSettings().setDomStorageEnabled(true);
		webView.requestFocus();
//        webView.setScrollBarStyle(0);
	}

    public static boolean checkCameraPermission(@NonNull Context context) {
        int permission = ContextCompat.checkSelfPermission(context, android.Manifest.permission.CAMERA);
        return permission == PackageManager.PERMISSION_GRANTED;
    }

	/**判断聊天界面是否正在运行
	 * @param context
	 * @return
	 */
	public static boolean isChatRunning(Context context) {
		ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningTaskInfo> mRunningTasks = manager.getRunningTasks(1);
		ActivityManager.RunningTaskInfo runningTaskInfo = mRunningTasks.get(0);
		if (runningTaskInfo != null) {
			return TextUtils.equals(runningTaskInfo.topActivity.getClassName(), "com.hemaapp.yjnh.chat.ChatPrivateActivity");
		}
		return false;
	}
}
